package cn.lingyangwl.framework.core;

import cn.hutool.core.util.RandomUtil;
import cn.lingyangwl.framework.core.thread.TtlThreadPoolTaskExecutor;
import cn.lingyangwl.framework.core.utils.AsyncTaskExecutorWithTx;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
@RestController
@RequestMapping("/asyncTaskExecutorWithTx")
public class AsyncTaskExecutorWithTxDemoController {
    public static ThreadPoolTaskExecutor getThreadPool() {
        ThreadPoolTaskExecutor executor = new TtlThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(10);
        // 线程队列最大线程数
        executor.setQueueCapacity(20);
        // 线程池中线程最大空闲存活时间
        executor.setKeepAliveSeconds(60);
        // 线程池最大线程数
        executor.setMaxPoolSize(100);
        executor.setThreadNamePrefix("taskExecutor-");
        // 核心线程是否允许超时，默认:false
        executor.setAllowCoreThreadTimeOut(false);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // IOC容器关闭时是否阻塞等待剩余的任务执行完成，默认:false（true则必须设置setAwaitTerminationSeconds）
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 阻塞IOC容器关闭的时间
        executor.setAwaitTerminationSeconds(60);

        executor.initialize();
        return executor;
    }

    public static String threadName() {
        return Thread.currentThread().getName();
    }

    @GetMapping
    public void t01() {
        AsyncTaskExecutorWithTx.init(getThreadPool())
                .addTask("task1", data -> System.out.println(threadName() + " " + data + " exec"))
                .addTask("task2", data -> System.out.println(threadName() + " " + data + " exec"))
                .addTask("task3", data -> System.out.println(threadName() + " " + data + " exec"))
                .addTask("task4", data -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println(threadName() + " " + data + " exec");
                        if (RandomUtil.randomInt(10) > 0) {
                            System.err.println("error");
                            throw new RuntimeException(threadName() + " " + data + " fail");
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                })
                .addTask("task5", data -> System.out.println(threadName() + " " + data + " exec"))
                .addTask("task6", data -> System.out.println(threadName() + " " + data + " exec")).execute();
    }
}
